<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <title>TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？ - L_B__</title><meta name="referrer" content="no-referrer">
<meta name="description" content="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？"><meta property="og:title" content="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？" />
<meta property="og:description" content="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://acking-you.github.io/posts/tcp%E4%B8%AD%E5%B7%B2%E6%9C%89so_keepalive%E9%80%89%E9%A1%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E5%9C%A8%E5%BA%94%E7%94%A8%E5%B1%82%E5%8A%A0%E5%85%A5%E5%BF%83%E8%B7%B3%E5%8C%85%E6%9C%BA%E5%88%B6/" /><meta property="og:image" content="https://acking-you.github.io/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2023-05-28T00:00:00+00:00" />
<meta property="article:modified_time" content="2023-05-28T00:00:00+00:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://acking-you.github.io/logo.png"/>

<meta name="twitter:title" content="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？"/>
<meta name="twitter:description" content="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？"/>
<meta name="application-name" content="FeelIt">
<meta name="apple-mobile-web-app-title" content="FeelIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="canonical" href="https://acking-you.github.io/posts/tcp%E4%B8%AD%E5%B7%B2%E6%9C%89so_keepalive%E9%80%89%E9%A1%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E5%9C%A8%E5%BA%94%E7%94%A8%E5%B1%82%E5%8A%A0%E5%85%A5%E5%BF%83%E8%B7%B3%E5%8C%85%E6%9C%BA%E5%88%B6/" /><link rel="prev" href="https://acking-you.github.io/posts/%E4%B8%80mysql%E6%9C%89%E5%93%AA%E4%BA%9B%E9%94%81/" /><link rel="next" href="https://acking-you.github.io/posts/redis%E5%B8%B8%E8%A7%81%E9%9D%A2%E8%AF%95%E9%A2%98/" /><link rel="stylesheet" href="/css/page.min.css"><link rel="stylesheet" href="/css/home.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/acking-you.github.io\/posts\/tcp%E4%B8%AD%E5%B7%B2%E6%9C%89so_keepalive%E9%80%89%E9%A1%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E5%9C%A8%E5%BA%94%E7%94%A8%E5%B1%82%E5%8A%A0%E5%85%A5%E5%BF%83%E8%B7%B3%E5%8C%85%E6%9C%BA%E5%88%B6\/"
        },"genre": "posts","keywords": "TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？","wordcount":  2580 ,
        "url": "https:\/\/acking-you.github.io\/posts\/tcp%E4%B8%AD%E5%B7%B2%E6%9C%89so_keepalive%E9%80%89%E9%A1%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E5%9C%A8%E5%BA%94%E7%94%A8%E5%B1%82%E5%8A%A0%E5%85%A5%E5%BF%83%E8%B7%B3%E5%8C%85%E6%9C%BA%E5%88%B6\/","datePublished": "2023-05-28T00:00:00+00:00","dateModified": "2023-05-28T00:00:00+00:00","publisher": {
            "@type": "Organization",
            "name": "作者"},"author": {
                "@type": "Person",
                "name": "作者"
            },"description": "TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？"
    }
    </script></head><body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="L_B__">L_B__</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="#" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="L_B__">L_B__</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="#" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="#" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><div class="menu-item"><a href="javascript:void(0);" class="theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div></div>
    </div>
</header><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single" data-toc="disable"><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/e5259f24f6a5a7fb2331d3fd0d18e631.png#pic_center"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/e5259f24f6a5a7fb2331d3fd0d18e631.png#pic_center, https://img-blog.csdnimg.cn/img_convert/e5259f24f6a5a7fb2331d3fd0d18e631.png#pic_center 1.5x, https://img-blog.csdnimg.cn/img_convert/e5259f24f6a5a7fb2331d3fd0d18e631.png#pic_center 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/e5259f24f6a5a7fb2331d3fd0d18e631.png#pic_center"
        title="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？" /></div><div class="single-card" data-image="true"><h2 class="single-title animated flipInX">TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？</h2><div class="post-meta">
                <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>作者</a></span>&nbsp;<span class="post-category">出版于  <a href="/categories/%E5%BF%83%E8%B7%B3%E5%8C%85%E8%AE%BE%E8%AE%A1/"><i class="far fa-folder fa-fw"></i>心跳包设计</a></span></div>
                <div class="post-meta-line"><span><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2023-05-28">2023-05-28</time></span>&nbsp;<span><i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 2580 字</span>&nbsp;
                    <span><i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 6 分钟</span>&nbsp;</div>
            </div>
            
            <hr><div class="details toc" id="toc-static"  data-kept="">
                    <div class="details-summary toc-title">
                        <span>目录</span>
                        <span><i class="details-icon fas fa-angle-right"></i></span>
                    </div>
                    <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#tcp-keepalive-选项">TCP keepalive 选项</a></li>
    <li><a href="#应用层的心跳包机制设计">应用层的心跳包机制设计</a></li>
  </ul>
</nav></div>
                </div><div class="content" id="content"><p>本文解释了 SO_KEEPALIVE 选项，和为什么要在应用层加入心跳包机制，以及心跳包机制如何设计的方方面面。</p>
<p>在实际开发中，我们需要处理下面两种情形中遇到的问题：</p>
<p><strong>情形一</strong>： 一个客户端连接服务器以后，如果长期没有和服务器有数据来往，可能会被防火墙程序关闭连接，有时候我们并不想要被关闭连接。例如，对于一个即时通讯软件，如果服务器没有消息时，我们确实不会和服务器有任何数据交换，但是如果连接被关闭了，有新消息来时，我们再也没法收到了，这就违背了“即时通讯”的设计要求。</p>
<p><strong>情形二</strong>：通常情况下，服务器与某个客户端一般不是位于同一个网络，其之间可能经过数个路由器和交换机，如果其中某个必经路由器或者交换器出现了故障，并且一段时间内没有恢复，导致这之间的链路不再畅通，而此时服务器与客户端之间也没有数据进行交换，由于 TCP 连接是状态机，对于这种情况，无论是客户端或者服务器都无法感知与对方的连接是否正常，这类连接我们一般称之为“死链”。</p>
<p><strong>情形一</strong>：中的应用场景要求必须保持客户端与服务器之间的连接正常，就是我们通常所说的“保活“。如上文所述，当服务器与客户端一定时间内没有有效业务数据来往时，我们只需要给对端发送心跳包即可实现保活。</p>
<p><strong>情形二</strong>中的死链，只要我们此时任意一端给对端发送一个数据包即可检测链路是否正常，这类数据包我们也称之为”心跳包”，这种操作我们称之为“心跳检测”。顾名思义，如果一个人没有心跳了，可能已经死亡了；一个连接长时间没有正常数据来往，也没有心跳包来往，就可以认为这个连接已经不存在，为了节约服务器连接资源，我们可以通过关闭 socket，回收连接资源。</p>
<p>根据上面的分析，让我再强调一下，心跳检测一般有两个作用：</p>
<ul>
<li>保活</li>
<li>检测死链</li>
</ul>
<h2 id="tcp-keepalive-选项">TCP keepalive 选项</h2>
<p>操作系统的 TCP/IP 协议栈其实提供了这个的功能，即 keepalive 选项。在 Linux 操作系统中，我们可以通过代码启用一个 socket 的心跳检测（即每隔一定时间间隔发送一个心跳检测包给对端），代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="c1">//on 是 1 表示打开 keepalive 选项，为 0 表示关闭，0 是默认值
</span><span class="c1"></span> <span class="kt">int</span> <span class="n">on</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
 <span class="n">setsockopt</span><span class="p">(</span><span class="n">fd</span><span class="p">,</span> <span class="n">SOL_SOCKET</span><span class="p">,</span> <span class="n">SO_KEEPALIVE</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">on</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">on</span><span class="p">));</span>
</code></pre></div><p>但是，即使开启了这个选项，这个选项默认发送心跳检测数据包的时间间隔是 7200 秒（2 小时），这时间间隔实在是太长了，不具有实用性。</p>
<p>当然，我们可以通过继续设置 keepalive 相关的三个选项来改变这个时间间隔，它们分别是 TCP_KEEPIDLE、TCP_KEEPINTVL 和 TCP_KEEPCNT，示例代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="c1">//发送 keepalive 报文的时间间隔
</span><span class="c1"></span> <span class="kt">int</span> <span class="n">val</span> <span class="o">=</span> <span class="mi">7200</span><span class="p">;</span>
 <span class="n">setsockopt</span><span class="p">(</span><span class="n">fd</span><span class="p">,</span> <span class="n">IPPROTO_TCP</span><span class="p">,</span> <span class="n">TCP_KEEPIDLE</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">val</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">val</span><span class="p">));</span>
 
 <span class="c1">//两次重试报文的时间间隔
</span><span class="c1"></span> <span class="kt">int</span> <span class="n">interval</span> <span class="o">=</span> <span class="mi">75</span><span class="p">;</span>
 <span class="n">setsockopt</span><span class="p">(</span><span class="n">fd</span><span class="p">,</span> <span class="n">IPPROTO_TCP</span><span class="p">,</span> <span class="n">TCP_KEEPINTVL</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">interval</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">interval</span><span class="p">));</span>
 
 <span class="kt">int</span> <span class="n">cnt</span> <span class="o">=</span> <span class="mi">9</span><span class="p">;</span>
 <span class="n">setsockopt</span><span class="p">(</span><span class="n">fd</span><span class="p">,</span> <span class="n">IPPROTO_TCP</span><span class="p">,</span> <span class="n">TCP_KEEPCNT</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">cnt</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">cnt</span><span class="p">));</span>
</code></pre></div><p>TCP_KEEPIDLE 选项设置了发送 keepalive 报文的时间间隔，发送时如果对端回复 ACK。则本端 TCP 协议栈认为该连接依然存活，继续等 7200 秒后再发送 keepalive 报文；如果对端回复 RESET，说明对端进程已经重启，本端的应用程序应该关闭该连接。</p>
<p>如果对端没有任何回复，则本端做重试，如果重试 9 次（TCP_KEEPCNT 值）（前后重试间隔为 75 秒（TCP_KEEPINTVL 值））仍然不可达，则向应用程序返回 ETIMEOUT（无任何应答）或 EHOST 错误信息。</p>
<p>我们可以使用如下命令查看 Linux 系统上的上述三个值的设置情况：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="p">[</span><span class="n">root</span><span class="err">@</span><span class="n">iZ238vnojlyZ</span> <span class="o">~</span><span class="p">]</span><span class="err">#</span> <span class="n">sysctl</span> <span class="o">-</span><span class="n">a</span> <span class="o">|</span> <span class="n">grep</span> <span class="n">keepalive</span>
 <span class="n">net</span><span class="p">.</span><span class="n">ipv4</span><span class="p">.</span><span class="n">tcp_keepalive_intvl</span> <span class="o">=</span> <span class="mi">75</span>
 <span class="n">net</span><span class="p">.</span><span class="n">ipv4</span><span class="p">.</span><span class="n">tcp_keepalive_probes</span> <span class="o">=</span> <span class="mi">9</span>
 <span class="n">net</span><span class="p">.</span><span class="n">ipv4</span><span class="p">.</span><span class="n">tcp_keepalive_time</span> <span class="o">=</span> <span class="mi">7200</span>
</code></pre></div><p>在 Windows 系统设置 keepalive 及对应选项的代码略有不同：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="c1">//开启 keepalive 选项
</span><span class="c1"></span> <span class="k">const</span> <span class="kt">char</span> <span class="n">on</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
 <span class="n">setsockopt</span><span class="p">(</span><span class="n">socket</span><span class="p">,</span> <span class="n">SOL_SOCKET</span><span class="p">,</span> <span class="n">SO_KEEPALIVE</span><span class="p">,</span> <span class="p">(</span><span class="kt">char</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">on</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">on</span><span class="p">);</span>
 
 <span class="c1">// 设置超时详细信息
</span><span class="c1"></span> <span class="n">DWORD</span> <span class="n">cbBytesReturned</span><span class="p">;</span>
 <span class="n">tcp_keepalive</span> <span class="n">klive</span><span class="p">;</span>
 <span class="c1">// 启用保活
</span><span class="c1"></span> <span class="n">klive</span><span class="p">.</span><span class="n">onoff</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
 <span class="n">klive</span><span class="p">.</span><span class="n">keepalivetime</span> <span class="o">=</span> <span class="mi">7200</span><span class="p">;</span>
 <span class="c1">// 重试间隔为10秒
</span><span class="c1"></span> <span class="n">klive</span><span class="p">.</span><span class="n">keepaliveinterval</span> <span class="o">=</span> <span class="mi">1000</span> <span class="o">*</span> <span class="mi">10</span><span class="p">;</span> 
 <span class="n">WSAIoctl</span><span class="p">(</span><span class="n">socket</span><span class="p">,</span> <span class="n">SIO_KEEPALIVE_VALS</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">klive</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">tcp_keepalive</span><span class="p">),</span> <span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">cbBytesReturned</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>
</code></pre></div><h2 id="应用层的心跳包机制设计">应用层的心跳包机制设计</h2>
<p>由于 keepalive 选项需要为每个连接中的 socket 开启，由于这不一定是必须的，可能会产生大量无意义的带宽浪费，且 keepalive 选项不能与应用层很好地交互，因此一般实际的服务开发中，还是建议读者在应用层设计自己的心跳包机制。那么如何设计呢？</p>
<p>从技术来讲，心跳包其实就是一个预先规定好格式的数据包，在程序中启动一个定时器，定时发送即可，这是最简单的实现思路。但是，如果通信的两端有频繁的数据来往，此时到了下一个发心跳包的时间点了，此时发送一个心跳包。这其实是一个流量的浪费，既然通信双方不断有正常的业务数据包来往，这些数据包本身就可以起到保活作用，为什么还要浪费流量去发送这些心跳包呢？</p>
<p>以我写的 NIO 网络库 netpoll-cpp 为例，为了检测死链，防止TCP短连接浪费大量资源，使用的策略是：把连接关闭资源释放这件事用一个回调来做，然后每次连接一旦有可读消息或者主动写入消息，都通过定时器添加一个回调，比如一有消息收发就添加30s后关闭连接的回调。</p>
<p>很明显如果直接每次定时器任务一触发就关闭连接，并不能起到延长生命周期的效果（因为后续添加的事件无法取消前面的事件），在 netpoll-cpp 中，这个定时任务其实是一个通过RAII封装的类，每次定时器里的任务队列只需要把该元素pop出来实现回调（调用析构函数），而析构函数是否调用就是另一个妙处了，我是通过引用计数来进行判断的，也就是说一个定时任务用 <code>shared_ptr</code> 进行封装，然后成员变量中留一份 <code>weak_ptr</code> ，这样就能够感知到该回调是否已经调用，如果调用了，那么引用计数将会为0，如果还没有调用，也就是延迟30s还没到，那么将 <code>weak_ptr</code> 升级为 <code>shared_ptr</code> 继续插入一个 30s 的任务，就算之前的任务触发，也不会调用回调，因为引用计数没有下降到0，这就是整个基于定时器的 C++ 中比较妙的心跳设计。</p>
<p>基于这个回调，我们只需要在这个类中加入一个 TCP 连接类的 <code>weak_ptr</code> 实例，只要 TCP 连接还存在，则关闭，否则啥也不做，这样同时实现了内存安全。</p>
<p>我们发现有了这样的底层回调的设计，灵活性和维护性将大大增加，但是定时器任务的触发存在比较大的消耗，但很明显，这个任务其实不需要很高精度的定时，所以 netpoll-cpp 中基于底层的定时器又加了一个时间轮实现的定时器，旨在将定时器任务的添加和任务的触发的性能消耗降到最低，具体可以看看我的博客 <a href="https://acking-you.github.io/posts/%E5%AE%9E%E7%8E%B0%E9%AB%98%E6%80%A7%E8%83%BD%E6%97%B6%E9%97%B4%E8%BD%AE%E7%94%A8%E4%BA%8E%E8%B8%A2%E5%87%BA%E7%A9%BA%E9%97%B2%E8%BF%9E%E6%8E%A5/" target="_blank" rel="noopener noreffer">实现高性能时间轮用于踢出空闲连接</a> 。</p>
<p>讲了这么多，最后总结具体检测死链和保活的心跳设计大家应该有很好的思路了，我的想法就是，把心跳的底层维护转化思路为延长连接的生命周期。比如需要检测死链，就只需要在每次收发数据包的时候延长生命周期即可，如果很久没有收发数据，那么该连接自然会被销毁。而保活也只需要你自己设计对应的心跳包，然后每次心跳包一旦触发就延长生命周期。</p>
<p>延长生命周期的代码逻辑如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"><span class="kt">void</span> <span class="n">TcpConnectionImpl</span><span class="o">::</span><span class="n">extendLife</span><span class="p">()</span>
<span class="p">{</span>
   <span class="k">if</span> <span class="p">(</span><span class="n">m_idleTimeout</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span>
   <span class="p">{</span>
      <span class="k">auto</span> <span class="n">now</span> <span class="o">=</span> <span class="n">Timestamp</span><span class="o">::</span><span class="n">now</span><span class="p">();</span>
      <span class="k">if</span> <span class="p">(</span><span class="n">now</span> <span class="o">&lt;</span> <span class="p">(</span><span class="n">m_lastTimingWheelUpdateTime</span> <span class="o">+</span> <span class="mf">1.0</span><span class="p">))</span> <span class="k">return</span><span class="p">;</span>
      <span class="n">m_lastTimingWheelUpdateTime</span> <span class="o">=</span> <span class="n">now</span><span class="p">;</span>
      <span class="k">auto</span> <span class="n">entry</span>                  <span class="o">=</span> <span class="n">m_kickoffEntry</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
      <span class="k">if</span> <span class="p">(</span><span class="n">entry</span><span class="p">)</span>
      <span class="p">{</span>
         <span class="k">auto</span> <span class="n">ptr</span> <span class="o">=</span> <span class="n">m_timingWheelWeakPtr</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
         <span class="k">if</span> <span class="p">(</span><span class="n">ptr</span><span class="p">)</span> <span class="n">ptr</span><span class="o">-&gt;</span><span class="n">insertEntry</span><span class="p">(</span><span class="n">m_idleTimeout</span><span class="p">,</span> <span class="n">entry</span><span class="p">);</span>
      <span class="p">}</span>
   <span class="p">}</span>
<span class="p">}</span>
</code></pre></div><p>具体源代码可以查看：<a href="https://github.com/ACking-you/netpoll-cpp/blob/master/netpoll/net/inner/tcp_connection_impl.cc#L144" target="_blank" rel="noopener noreffer">https://github.com/ACking-you/netpoll-cpp/blob/master/netpoll/net/inner/tcp_connection_impl.cc</a></p>
</div><div class="post-footer" id="post-footer">
    <div class="post-info"><div class="post-info-tag"><span><a href="/tags/tcp%E4%B8%AD%E5%B7%B2%E6%9C%89so_keepalive%E9%80%89%E9%A1%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E5%9C%A8%E5%BA%94%E7%94%A8%E5%B1%82%E5%8A%A0%E5%85%A5%E5%BF%83%E8%B7%B3%E5%8C%85%E6%9C%BA%E5%88%B6/">TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？</a>
                </span></div><div class="post-info-line"><div class="post-info-mod">
                <span>更新于 2023-05-28</span>
            </div><div class="post-info-mod"></div>
        </div><div class="post-info-share">
            <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://acking-you.github.io/posts/tcp%E4%B8%AD%E5%B7%B2%E6%9C%89so_keepalive%E9%80%89%E9%A1%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E5%9C%A8%E5%BA%94%E7%94%A8%E5%B1%82%E5%8A%A0%E5%85%A5%E5%BF%83%E8%B7%B3%E5%8C%85%E6%9C%BA%E5%88%B6/" data-title="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？" data-hashtags="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://acking-you.github.io/posts/tcp%E4%B8%AD%E5%B7%B2%E6%9C%89so_keepalive%E9%80%89%E9%A1%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E5%9C%A8%E5%BA%94%E7%94%A8%E5%B1%82%E5%8A%A0%E5%85%A5%E5%BF%83%E8%B7%B3%E5%8C%85%E6%9C%BA%E5%88%B6/" data-hashtag="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://acking-you.github.io/posts/tcp%E4%B8%AD%E5%B7%B2%E6%9C%89so_keepalive%E9%80%89%E9%A1%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E5%9C%A8%E5%BA%94%E7%94%A8%E5%B1%82%E5%8A%A0%E5%85%A5%E5%BF%83%E8%B7%B3%E5%8C%85%E6%9C%BA%E5%88%B6/" data-title="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？" data-web><i class="fab fa-whatsapp fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://acking-you.github.io/posts/tcp%E4%B8%AD%E5%B7%B2%E6%9C%89so_keepalive%E9%80%89%E9%A1%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E5%9C%A8%E5%BA%94%E7%94%A8%E5%B1%82%E5%8A%A0%E5%85%A5%E5%BF%83%E8%B7%B3%E5%8C%85%E6%9C%BA%E5%88%B6/" data-title="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？"><i class="fab fa-line fa-fw"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://acking-you.github.io/posts/tcp%E4%B8%AD%E5%B7%B2%E6%9C%89so_keepalive%E9%80%89%E9%A1%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E5%9C%A8%E5%BA%94%E7%94%A8%E5%B1%82%E5%8A%A0%E5%85%A5%E5%BF%83%E8%B7%B3%E5%8C%85%E6%9C%BA%E5%88%B6/" data-title="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？" data-image="https://img-blog.csdnimg.cn/img_convert/e5259f24f6a5a7fb2331d3fd0d18e631.png#pic_center"><i class="fab fa-weibo fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Myspace" data-sharer="myspace" data-url="https://acking-you.github.io/posts/tcp%E4%B8%AD%E5%B7%B2%E6%9C%89so_keepalive%E9%80%89%E9%A1%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E5%9C%A8%E5%BA%94%E7%94%A8%E5%B1%82%E5%8A%A0%E5%85%A5%E5%BF%83%E8%B7%B3%E5%8C%85%E6%9C%BA%E5%88%B6/" data-title="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？" data-description="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？"><i data-svg-src="/lib/simple-icons/icons/myspace.min.svg"></i></a><a href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://acking-you.github.io/posts/tcp%E4%B8%AD%E5%B7%B2%E6%9C%89so_keepalive%E9%80%89%E9%A1%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E5%9C%A8%E5%BA%94%E7%94%A8%E5%B1%82%E5%8A%A0%E5%85%A5%E5%BF%83%E8%B7%B3%E5%8C%85%E6%9C%BA%E5%88%B6/" data-title="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？" data-description="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？"><i class="fab fa-blogger fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Evernote" data-sharer="evernote" data-url="https://acking-you.github.io/posts/tcp%E4%B8%AD%E5%B7%B2%E6%9C%89so_keepalive%E9%80%89%E9%A1%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E5%9C%A8%E5%BA%94%E7%94%A8%E5%B1%82%E5%8A%A0%E5%85%A5%E5%BF%83%E8%B7%B3%E5%8C%85%E6%9C%BA%E5%88%B6/" data-title="TCP中已有SO_KEEPALIVE选项，为什么还要在应用层加入心跳包机制？"><i class="fab fa-evernote fa-fw"></i></a></span>
        </div></div><div class="post-nav"><a href="/posts/%E4%B8%80mysql%E6%9C%89%E5%93%AA%E4%BA%9B%E9%94%81/" class="prev" rel="prev" title="一、MySQL有哪些锁"><i class="fas fa-angle-left fa-fw"></i>Previous Post</a>
            <a href="/posts/redis%E5%B8%B8%E8%A7%81%E9%9D%A2%E8%AF%95%E9%A2%98/" class="next" rel="next" title="Redis常见面试题">Next Post<i class="fas fa-angle-right fa-fw"></i></a></div></div>
</div></article></div>
            </main>
            <footer class="footer"><div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.86.0">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/khusika/FeelIt" target="_blank" rel="noopener noreffer" title="FeelIt 1.0.1"><i class="fas fa-hand-holding-heart fa-fw"></i> FeelIt</a>
        </div><div class="footer-line" itemscope itemtype="http://schema.org/CreativeWork"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2023</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/"></a></span></div>
</div>
</footer>
        </div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-chevron-up fa-fw"></i>
            </a></div><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><link rel="stylesheet" href="/lib/katex/katex.min.css"><link rel="stylesheet" href="/lib/katex/copy-tex.min.css"><script src="/lib/autocomplete/autocomplete.min.js"></script><script src="/lib/lunr/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="/lib/lazysizes/lazysizes.min.js"></script><script src="/lib/clipboard/clipboard.min.js"></script><script src="/lib/sharer/sharer.min.js"></script><script src="/lib/katex/katex.min.js"></script><script src="/lib/katex/auto-render.min.js"></script><script src="/lib/katex/copy-tex.min.js"></script><script src="/lib/katex/mhchem.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":200},"comment":{},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":100,"noResultsFound":"没有找到结果","snippetLength":50,"type":"lunr"}};</script><script src="/js/theme.min.js"></script></body></html>
